package com.easy.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class imageUtil {
    private static final String ENDPOINT="oss-cn-beijing.aliyuncs.com";
    private static final String BUCKET_NAME="barbershop888";
    private static final String ACCESS_KEY_ID="LTAI5t6ymiuj6G7SbLMSAEVk";
    private static final String ACCESS_KEY_SECRET="PiiNOJnKLeQ9LH2rMIgcABESGdTYuO";

    private static final OSS ossClient=new OSSClientBuilder().build("https://"+ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);

    public static String upload(InputStream is, String filename){
        String newFileName= UUID.randomUUID().toString()+filename.substring(filename.lastIndexOf("."));
        OSS ossClient=new OSSClientBuilder().build("https://"+ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
        //请求对象
        PutObjectRequest request=new PutObjectRequest(BUCKET_NAME,newFileName,is);
        //响应对象
        PutObjectResult result=ossClient.putObject(request);
        return "https://"+ BUCKET_NAME+"."+ ENDPOINT+"/"+newFileName;
    }

    public static void delete(String fileName){
        ossClient.deleteObject(BUCKET_NAME,fileName);
    }

    public static List<String> getFileList(){
        List<String>list=new ArrayList<>();
        ListObjectsRequest request=new ListObjectsRequest(BUCKET_NAME);
        request.setMarker(null);
        request.setMaxKeys(1000);
        ObjectListing objectListing =ossClient.listObjects(request);
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()){
            list.add(objectSummary.getKey());
        }
        return list;
    }

    public static void main(String[] args) {
        System.out.println(getFileList());

//        try {
//            File file=new File("D:\\Java study\\uploadfile\\123.png");
//            InputStream is=new FileInputStream(file);
//            String newFileName=upload(is,file.getName());
//            System.out.println(newFileName);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

}
